//
//  LXArtistViewController.m
//  bgms_d
//
//  Created by lachesis-zhu on 2019/1/18.
//  Copyright © 2019 lachesis-zhu. All rights reserved.
//

#import "LXArtistViewController.h"
#import "ZYPlayingViewController.h"
#import "GLMusicListViewController.h"
#import "GLMiniMusicView.h"
#import "ZYMusicTool.h"
#import "ZYMusic.h"
#import "LXPatientsHeaderView.h"

@interface LXArtistViewController () <UITableViewDelegate, UITableViewDataSource, LXPatientsHeaderViewDelegate>

@property (nonatomic, strong) IBOutlet UITableView *tableView;
@property (nonatomic, strong) NSDictionary *storyMusicDic;
@property (nonatomic, strong) NSMutableDictionary *listYesOrNodic;
@property (nonatomic, strong) NSArray *artistKeyArrays;
@end


@implementation LXArtistViewController

#pragma mark -  public method
#pragma mark -  life cycle
- (void)dealloc
{
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self initializationData];
    [self addNotification];
    
    [self loadUI];
    [self buildNavi];
    
    [self loadViewDatas];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
}

#pragma mark -  over write

#pragma mark -  setter & getter
- (void)setArtistsListDic:(NSMutableDictionary *)artistsListDic {
    NSArray *kArrSort = [artistsListDic allKeys];
    self.artistKeyArrays = [kArrSort sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
        return [obj1 compare:obj2 options:NSNumericSearch];
    }];
    _artistsListDic = artistsListDic;
    if (!self.storyMusicDic) {
        self.storyMusicDic = [[NSDictionary alloc] initWithDictionary:artistsListDic];
    }
    [self.tableView reloadData];
}

- (void)setSearchString:(NSString *)searchString {
    _searchString = searchString;
    NSArray *keyArrays = self.storyMusicDic.allKeys;
    NSMutableDictionary *searchDic = [[NSMutableDictionary alloc] init];
    __weak typeof(self) weakSelf = self;
    [keyArrays enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        NSMutableArray *searchArray = [[NSMutableArray alloc] init];
        NSString *key = obj;
        NSArray *songs = weakSelf.storyMusicDic[key];
        if ([key rangeOfString:searchString].location != NSNotFound) {
            searchArray = [[NSMutableArray alloc] initWithArray:songs];
        } else {
            [songs enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                ZYMusic *music = obj;
                if ([music.name rangeOfString:searchString].location != NSNotFound) {
                    [searchArray addObject:music];
                }
            }];
        }
        if (searchArray.count > 0) {
            [searchDic setObject:searchArray forKey:key];
        }
    }];
    self.artistsListDic = [[NSMutableDictionary alloc] initWithDictionary:searchDic];
}

- (void)setCancelSearch:(BOOL)cancelSearch
{
    _cancelSearch = cancelSearch;
    self.artistsListDic = [[NSMutableDictionary alloc] initWithDictionary:self.storyMusicDic];
    [self.tableView reloadData];
}
#pragma mark -  private method
- (void)initializationData
{
    
}

- (void)loadUI
{
    self.view.backgroundColor = kAppLightBackgroundColor;
    self.tableView.separatorColor = UICOLOR_FROM_RGB(45, 185, 105);
    self.tableView.tableFooterView = [[UIView alloc] init];
    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"musiclist"];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
}

- (void)loadViewDatas
{
    
}

- (void)buildNavi
{
    
}

#pragma mark -  notification
- (void)addNotification
{
    
}

#pragma mark -  network


#pragma mark -  event handle


#pragma mark -  delegate
#pragma mark tableViewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    NSArray *array = self.artistsListDic.allKeys;
    return array.count;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    LXPatientsHeaderView *headView = [[LXPatientsHeaderView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, [LXAutoLength lx_L:75])];
    headView.section = section;
    headView.headerViewDelegate = self;
    [headView setBackgroundColor:[UIColor whiteColor]];
    [headView drawAroundViewWithLocation:DrawBottom color:kAppGrayTextColor insets:UIEdgeInsetsMake(-0.5, 0, 0, 0)];
    
    NSArray *songs = self.artistsListDic[self.artistKeyArrays[section]];
    [headView.showLab setText:self.artistKeyArrays[section]];
    headView.numberLab.text = [NSString stringWithFormat:@"%ld songs", songs.count];
    
    [headView.selectImage setImage:[UIImage imageNamed:@"icon_xiala"]];
    NSString *key = [NSString stringWithFormat:@"%ld", section];
    NSString *valueStr = [self.listYesOrNodic valueForKey:key];
    if ([valueStr isEqualToString:@"YES"]) {
        [headView changeToRightAnimated];
    }
    
    return headView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return [LXAutoLength lx_L:75];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *valueStr = [_listYesOrNodic valueForKey:[NSString stringWithFormat:@"%ld", indexPath.section]];
    if ([valueStr isEqualToString:@"YES"]) {
        return [LXAutoLength lx_L:60];
    } else {
        return 0;
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    NSString *valueStr = [_listYesOrNodic valueForKey:[NSString stringWithFormat:@"%ld", section]];
    if ([valueStr isEqualToString:@"YES"]) {
        NSArray *songs = self.artistsListDic[self.artistKeyArrays[section]];
        return songs.count;
    } else {
        return 0;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"musiclist" forIndexPath:indexPath];
    UILabel *text = [cell.contentView viewWithTag:1];
    if (!text) {
        text = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, [LXAutoLength lx_L:60])];
        text.tag = 1;
        text.font = [UIFont systemFontOfSize:15];
        text.textColor = kAppNormalTextColor;
        text.textAlignment = NSTextAlignmentCenter;
        [cell.contentView addSubview:text];
        [cell.contentView drawAroundViewWithLocation:DrawBottom color:kAppLinesColor insets:UIEdgeInsetsMake(0, 0, 0.5, 0)];
    }
    NSArray *songs = self.artistsListDic[self.artistKeyArrays[indexPath.section]];
    ZYMusic *music = songs[indexPath.row];
    text.text = music.name;
    MPMediaItem *lastItem = [ZYAudioManager defaultManager].nowPlayItem;
    if (lastItem && [lastItem isEqual:music.item]) {
        cell.contentView.backgroundColor = kAppSelectedColor;
    } else {
        cell.contentView.backgroundColor = kAppThemeColor;
    }
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    NSArray *songs = self.artistsListDic[self.artistKeyArrays[indexPath.section]];
    ZYMusic *music = songs[indexPath.row];
    [(GLMusicListViewController *)self.containerController selectPlayMusic:music withAlbum:nil];
    self.artistsListDic = [[NSMutableDictionary alloc] initWithDictionary:self.storyMusicDic];
}

#pragma mark  LXPatientsHeaderViewDelegate
- (void)patientsHeaderView:(LXPatientsHeaderView *)patientsHeaderView event:(UIGestureRecognizer *)event
{
    NSString *key = [NSString stringWithFormat:@"%ld", patientsHeaderView.section];
    NSString *valueStr = [self.listYesOrNodic valueForKey:key];
    
    NSArray *songs = self.artistsListDic[self.artistKeyArrays[patientsHeaderView.section]];
    if ([valueStr isEqualToString:@"YES"]) {
        if (patientsHeaderView.positionType == BottomType) {
            [patientsHeaderView changeToLeftAnimated];
            [self.listYesOrNodic setValue:@"NO" forKey:key];
            NSMutableArray *indexPaths = [NSMutableArray array];
            for (int i = 0; i < songs.count; i++) {
                [indexPaths addObject:[NSIndexPath indexPathForItem:i inSection:patientsHeaderView.section]];
            }
            [self.tableView deleteRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationFade];
        }
    } else {
        if (patientsHeaderView.positionType == RightType) {
            [patientsHeaderView changeToRightAnimated];
            [self.listYesOrNodic setValue:@"YES" forKey:key];
            NSMutableArray *indexPaths = [NSMutableArray array];
            for (int i = 0; i < songs.count; i++) {
                [indexPaths addObject:[NSIndexPath indexPathForItem:i inSection:patientsHeaderView.section]];
            }
            [self.tableView insertRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationFade];
            NSIndexPath *indexPath = [indexPaths lastObject];
            [self.tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionMiddle animated:YES];
        }
    }
}

#pragma mark -  LazyLoad Method
- (NSMutableDictionary *)listYesOrNodic {
    if (!_listYesOrNodic) {
        _listYesOrNodic = [[NSMutableDictionary alloc] init];
    }
    return _listYesOrNodic;
}
@end
